﻿using System;
using System.Collections.Generic;
using Cipyar.Core.DomainObjects;
using SevenZip;

namespace Cipyar.Core
{
    public class FileManager
    {
        private readonly ConfigurationManager _configurationManager;

        public FileManager()
        {
            _configurationManager = ConfigurationManager.GetDefaultConfigurationManager();
        }

        public FileManager(string settingFileName)
        {
            _configurationManager = ConfigurationManager.GetConfigurationManager(settingFileName);
        }

        public ConfigurationManager ConfigurationManager
        {
            get { return _configurationManager; }
        }

        internal string GetCompressedFile(Compression compression, string[] files)
        {
            SevenZipCompressor compressor = ConfigurationManager.GetSevenZipCompressor(compression);
            ConfigurationManager.SetEncryptionSettings(compressor, compression);
            return CompressFiles(compressor, compression.Encryption.Enabled, files);
        }

        internal string CompressFiles(SevenZipCompressor compressor, bool encrypted, string[] files)
        {
            List<object> param = new List<object>();
            List<Type> paramTypes = new List<Type>();

            ConfigurationManager.CreateNewCompressedFileName();
            param.Add(ConfigurationManager.CompressedFileName);
            paramTypes.Add(typeof (string));

            string compressFilesMethodName = "CompressFiles";
            if (encrypted)
            {
                param.Add(ConfigurationManager.Password);
                paramTypes.Add(typeof(string));
                compressFilesMethodName += "Encrypted";
            }
            param.Add(files);
            paramTypes.Add(typeof(string[]));
            
            typeof (SevenZipCompressor).GetMethod(compressFilesMethodName, paramTypes.ToArray()).Invoke(compressor, param.ToArray());
            return param[0] as string;
        }

        public string[] GetFiles()
        {
            if (ConfigurationManager.Settings.Files.Compression.Enabled) 
                return new[] {GetCompressedFile(ConfigurationManager.Settings.Files.Compression, ConfigurationManager.Settings.Files.File)};
            return ConfigurationManager.Settings.Files.File;
        }
    }
}
